package com.iot08.api.service.active;

import com.iot08.common.entity.app.active.WeekActive;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * @author weichao 1299101858@qq.com
 * @version 1.0
 * @date 4/29/22 2:40 PM
 */
@Slf4j
@Service
public class WeekActiveService extends BaseService<WeekActive> {
    public void add(WeekActive baseActive) {
        String td = DateUtil.dateToStr(new Date(), DateUtil.FORMAT_4);
        baseActive.setDate(td);
        baseActive.setExpiryAt(this.getLastDayOfWeek(new Date()));
        this.save(baseActive);
    }

    /**
     * 取得指定日期所在周的本周最后一天的 23:59:59
     * @param date
     * @time: 4/29/22 4:35 PM
     * @author: Weichao
     * @version 1.0
     */

    public Date getLastDayOfWeek(Date date) {

        Calendar c = new GregorianCalendar();

        c.setFirstDayOfWeek(Calendar.MONDAY);

        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday

        return c.getTime();

    }


    public static void main(String[] args){
        WeekActiveService weekActiveService = new WeekActiveService();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date testDate = new Date();
        testDate = DateUtil.strToDate("2022-02-15");
        System.out.println(String.format("取得指定日期所在周的本周最后一天的 23:59:59  %s", format.format(weekActiveService.getLastDayOfWeek(testDate))));
    }
}
